'''
views
'''
import sys
import json
from django.shortcuts import (render, redirect)
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from vsphere.lib.vm import (get_vms_info, delete_vm, deploy_vm,
                            poweroff_vm, init_vminfo, power_action_vm,
                            remove_disk_from_vm, add_disk_to_vm)
from vsphere.lib import vmdisk as vmdisk_lib
from vsphere.lib.ttypes import RC, to_message, DeployRequest
from common.result_entity import HttpJsonResult
from vsphere.models import (DeployParam, VMInfo, VMSumInfo, get_vm_sum,
                            get_vms_data, VMDiskInfo)

from django.contrib import admin
import re
# import ast


# Initialize vm info
if 'runserver' in sys.argv:
    init_vminfo(debug=True)


# Create your views here.

@login_required
def index(request, order=None, reverse=None):
    """TODO: Docstring for index.

    :request: TODO
    :returns: TODO

    """
    # VM_INFO_SAMPLE_ = re.sub("(?<=\d{1})L(?!\s*([\'\"]|\w+))", "",
                    #   str(VM_INFO_SAMPLE))
    # VM_INFO_SAMPLE_ = ast.literal_eval(VM_INFO_SAMPLE_)
    # VM_INFO_SAMPLE = get_vms_info()
    # pickle.load()
    # print order_by
    vm_info = get_vms_data(orderkey=order, reverse=reverse)
    vm_sum_info = get_vm_sum()
    # print vm_info
    # print vm_sum_info
    # response = serializers.serialize('json', vm_info)
    # print response
    # print vm_sum_info
    for item in vm_info:
        encode_dict(item)
    return render(request, 'index.html',
                  {'vm_info': vm_info, 'vm_sum_info': vm_sum_info})

def vm_detail(request, uuid):
    print "++++++++++++++++++++", uuid
    disks_info = VMDiskInfo.objects.filter(vm_uuid__uuid=uuid) #.get(vm_uuid__exact=uuid)
    vm_info = VMInfo.objects.get(uuid__exact=uuid)
    # print vm_info
    # print disks_info[0].__dict__

    # for disk in disks_info:
    # print list(disks_info)
    # from django.core import serializers
    # print serializers.serialize("json", disks_info)
    # print serializers.serialize("json", disks_info[0])
    # for disk in list(disks_info):
        # serializers.
    # from copy import deepcopy
    # vm_info = deepcopy(disk_info.vm_uuid)
    # disk_info.vm_uuid = None
    # disk_info._state = None
    # vm_info._state = None
    # vm_info = VMInfo.objects.get(uuid__exact=uuid)
    # print disk_info
    # print vm_info.__dict__

    data = {"disks_info": disks_info, "vm_info": vm_info}
    # data = ""
    print data
    return render(request, "detail.html", data)


def encode_dict(d, codec='utf8'):
    ks = d.keys()
    for k in ks:
        val = d.pop(k)
        if isinstance(val, unicode):
            val = val.encode(codec)
        elif isinstance(val, dict):
            val = encode_dict(val, codec)
        if isinstance(k, unicode):
            k = k.encode(codec)
        d[k] = val
    return d

@login_required
@csrf_exempt
def delete(request):
    """Delete VM by uuid
    request.POST: vms_uuid

    """
    if request.method == 'POST':
        # request.POST.getlist('vms_uuid_list[]')
        vms_uuid_str = request.POST.get('vms_uuid_list')

        if not vms_uuid_str:
            return HttpJsonResult(RC.ERROR, to_message(RC.ERROR))
        vms_uuid = json.loads(vms_uuid_str)
    else:
        return HttpJsonResult(RC.INVALID_METHOD, to_message(RC.INVALID_METHOD))
    try:
        delete_vm(vms_uuid)
    except Exception as e:
        print "Failed to remove %s (%s)" % (str(vms_uuid), str(e))
        return HttpJsonResult(RC.DELETE_VM_ERROR,
                              to_message(RC.DELETE_VM_ERROR))
    return HttpJsonResult(RC.PASS, to_message(RC.PASS))

# @login_required
@csrf_exempt
def poweron(request):
    if request.method == 'POST':
        vms_uuid = request.POST.get('vms_uuid_list', None)
        print vms_uuid
        vms_uuid = json.loads(vms_uuid)
        print vms_uuid
        if vms_uuid is None:
            return HttpJsonResult(RC.ERROR, to_message(RC.ERROR))
    else:
        return HttpJsonResult(RC.INVALID_METHOD,
                              to_message(RC.INVALID_METHOD))

    try:
        power_action_vm(vms_uuid, 'poweron')
    except Exception as e:
        print "Failed to poweron %s (%s)" % (str(vms_uuid), str(e))
        return HttpJsonResult(RC.POWEROFF_VM_ERROR,
                              to_message(RC.POWEROFF_VM_ERROR))

    return HttpJsonResult(RC.PASS, to_message(RC.PASS))

# @login_required
@csrf_exempt
def poweroff(request):
    if request.method == 'POST':
        vms_uuid = request.POST.get('vms_uuid_list', None)
        vms_uuid = json.loads(vms_uuid)
        if vms_uuid is None:
            return HttpJsonResult(RC.ERROR, to_message(RC.ERROR))
    else:
        return HttpJsonResult(RC.INVALID_METHOD,
                              to_message(RC.INVALID_METHOD))

    try:
        power_action_vm(vms_uuid, 'poweroff')
    except Exception as e:
        print "Failed to poweroff %s (%s)" % (str(vms_uuid), str(e))
        return HttpJsonResult(RC.POWEROFF_VM_ERROR,
                              to_message(RC.POWEROFF_VM_ERROR))

    return HttpJsonResult(RC.PASS, to_message(RC.PASS))


# def detail(request):
#     return render(request, 'detail.html')


def deploy(request):
    if request.method == 'GET':
        return render(request, 'deploy.html')
    elif request.method == 'POST':
        deploy_request = DeployRequest(request.POST)
        deploy_vm(deploy_request)
        return render(request, 'deploy_finish.html')


def remove_disk(request, uuid):
    if request.method == 'POST':
        wwid = request.POST.get('wwid')
    if wwid:
        print wwid
        scsi_num = re.search(r'(?<=SCSI).{5,6}', wwid).group()
        print scsi_num
    if scsi_num:
        remove_disk_from_vm(uuid, scsi_num)
        VMDiskInfo.objects.filter(wwid=wwid).delete()
    return redirect("vm_detail", uuid=uuid)


def add_disk(request, uuid):
    print "Enter add disk"
    if request.method == 'POST':
        wwid = request.POST.get('wwid')
        size = request.POST.get('size')
        provision = request.POST.get('provisiontype', 'thin')
        mode = request.POST.get('disk_mode', 'independent_persistent')

        size_str = size.encode("utf-8")
        size_num = int(size_str)
        print type(size_num)
        size = '%s GB' % size_str
        print type(size_num)
    if wwid:
        print wwid, size, provision, mode, type(size)
        scsi_num = re.search(r'(?<=SCSI).{5,6}', wwid).group()
        print scsi_num
    if scsi_num:
        # vmdisk = vmdisk_lib.VirtualDisk(uuid,
                                        # disk_size_gb=size,
                                        # disk_provision_type=provision,
                                        # disk_mode='independent_persisten')
        add_disk_to_vm(uuid, scsi_num, size_gb=size_num, provision_type=provision,
                       mode=mode)
        vm_info = VMInfo.objects.get(uuid__exact=uuid)
        # vm_disk = VMDiskInfo.objects.create()
        pd = VMDiskInfo(vm_uuid=vm_info,
                        wwid=wwid,
                        size=size,
                        diskMode=mode,
                        thinProvisioned=True if provision == 'thin' else False,
                        capacityInKB=size_num * 1024)

        pd.save()
    return redirect("vm_detail", uuid=uuid)
